package com.jhy.guavacase.io;

import com.google.common.io.ByteSource;
import com.google.common.io.Files;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.IOException;

/**
 * @author jhy
 * @ClassName ByteSourceCase.java
 * @Description ByteSource的示例
 * @createTime 2022年03月14日 19:38:00
 */
public class ByteSourceCase {

    private final String SOURCE_FILE = "E:\\java项目\\Guava学习\\guava-case\\guava-case\\src\\main\\resources\\io\\byteFile.txt";

    //1.测试ByteSource的read方法
    //可以将ByteSource理解为java自带的InputStream
    @Test
    public void testByteSourceRead() throws IOException {
        File sourceFile = new File(SOURCE_FILE);
        ByteSource byteSource = Files.asByteSource(sourceFile);
        byte[] read = byteSource.read();
        for (int i = 0; i < read.length; i++) {
            System.out.println(read[i] - '0'); //读出的为ascii码(txt中为char形式)，
        }
    }

    //2.slice切片的方法，指定开始位置offset和读取长度length即可
    @Test
    public void testByeSourceSlice() throws IOException {

        ByteSource byteSource = ByteSource.wrap(new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
        //切片
        ByteSource sliceByteSource = byteSource.slice(5, 5);
        byte[] read = sliceByteSource.read();
        for (int i = 0; i < read.length; i++) {
            System.out.println(read[i]); //读出的就是二进制byte
        }
    }

}
